package com.example.ec.controller;

import com.example.ec.model.User;
import com.example.ec.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Controller
@RequestMapping("user")
public class UserController extends BaseController {

    private UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("signUp")
    private String signUp(User user, MultipartFile file) throws IOException {
        if (userService.queryOne("queryUserByUsername", user) != null) {
            request.setAttribute("error", "该用户名已经存在,请换一个名字");
            return "redirect:sign_up.jsp";
        }
        userService.create(user);
        return "redirect:/index.jsp";
    }

    @PostMapping("signIn")
    private String signIn(User user) {
        user = userService.queryOne("queryUserByUsernameAndPassword", user);
        if (user == null) {
            request.setAttribute("error", "用户名或密码错误");
            return "/index.jsp";
        }
        session.setAttribute("user", user);
        if (user.getRole() == 0) {
            return "redirect:/product/index.jsp";
        } else {
            session.setAttribute("users", userService.queryList("queryAllUsers", null));
            return "redirect:/product/admin.jsp";
        }
    }

}
